package com.ktg.mes.pro.service.impl;

import java.util.*;
import com.alibaba.fastjson.JSONObject;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.mes.pro.domain.ProRouteProcess;
import com.ktg.mes.pro.service.IProRouteProcessService;
import com.ktg.mes.rec.domain.RecLnspectionRecord;
import com.ktg.mes.rec.domain.RecProcessesExt;
import com.ktg.mes.rec.service.IRecProcessesExtService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.pro.mapper.ProWaringMapper;
import com.ktg.mes.pro.domain.ProWaring;
import com.ktg.mes.pro.service.IProWaringService;



/**
 * 收录生产警告警告Service业务层处理
 *
 * @author byteco
 * @date 2022-11-28
 */
@Service
public class ProWaringServiceImpl extends ServiceImpl<ProWaringMapper, ProWaring> implements IProWaringService
{

    @Autowired
    private IProRouteProcessService proRouteProcessService;

    @Autowired
    private IRecProcessesExtService recProcessesExtService;

    /**
     * 查询收录生产警告警告
     *
     * @param entity 收录生产警告警告
     * @param page 分页对象
     * @return 收录生产警告警告
     */
    @Override
    public IPage<ProWaring> queryPageList(ProWaring entity, Page<ProWaring> page) {
        QueryWrapper<ProWaring> lqw = new QueryWrapper<>(entity);
        lqw.orderByDesc("create_time");
        IPage<ProWaring> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询收录生产警告警告
     *
     * @param entity 收录生产警告警告
     * @return 收录生产警告警告
     */
    @Override
    public List<ProWaring> queryList(ProWaring entity) {
        QueryWrapper<ProWaring> lqw = new QueryWrapper<>(entity);
        lqw.orderByDesc("create_time");
        return this.list(lqw);
    }

    public ProWaring getInfo(Long id)
    {
        return this.getById(id);
    }


    /**
     * 新增收录生产警告警告
     *
     * @param entity 收录生产警告警告
     * @return 结果
     */
    @Override
    public void insert(ProWaring entity)
    {
        entity.setCreateTime(DateUtils.getNowDate());
        this.save(entity);
    }

    /**
     * 修改收录生产警告警告
     *
     * @param entity 收录生产警告警告
     * @return 结果
     */
    @Override
    public boolean update(ProWaring entity)
    {
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }

    /**
     * 批量删除收录生产警告警告
     *
     * @param ids 需要删除的收录生产警告警告主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] ids)
    {

        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 删除收录生产警告警告信息
     *
     * @param id 收录生产警告警告主键
     * @return 结果
     */
    @Override
    public boolean delete(Long id)
    {
        return this.removeById(id);
    }


    /**
     * 判断工序参数是否超标，超标需要保存警告记录
     * @param entity
     */
    @Override
    public void isWarning(final RecLnspectionRecord entity,String desStr){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //提前设置需要警告的信息
                ProWaring proWaring = new ProWaring();
                proWaring.setType(ProWaring.type采集记录);
                proWaring.setUpdateTime(new Date());
                proWaring.setTaskName(entity.getTaskName());
                proWaring.setBatchNo(entity.getBatchNo());
                proWaring.setDeviceCode(entity.getMachineryCode());
                proWaring.setDeviceName(entity.getMachineryName());
                proWaring.setProcessName(entity.getProcessesName());
                proWaring.setBucket(entity.getToolTypeName());
                proWaring.setRecordId(entity.getId().toString());
                proWaring.setMachineryDataId(entity.getId());

                try{

                    //获取工序配置项实际参数值
                    ProRouteProcess proRouteProcess = proRouteProcessService.getById(entity.getProcessesId());

                    boolean isNeedWaring = false;
                    String desString = desStr;
                    if (proRouteProcess == null){
                        isNeedWaring = true;
                        desString = "工序配置数据获取失败！";
                    }else {
                        //获取工艺流程配置项，后台字段 对于 PDA字段
                        RecProcessesExt recProcessesExt = new RecProcessesExt();
                        recProcessesExt.setProcessId(entity.getProcessesId());
                        QueryWrapper<RecProcessesExt> recProcessesExtQueryWrapper = new QueryWrapper<>();
                        List<RecProcessesExt> mapList = recProcessesExtService.list(recProcessesExtQueryWrapper);

                        //后台字段 对于 PDA字段
                        Map<String,RecProcessesExt> mapPdaName = new HashMap<>();
                        for (int i = 0; i < mapList.size(); i++) {
                            JSONObject jsonObject = JSONObject.parseObject(mapList.get(i).getRuleBackstage());
                            if (jsonObject != null && jsonObject.getString("type") != null){
                                if (jsonObject.getString("type").equals("input")  || jsonObject.getString("type").equals("singleChoice")){
                                    mapPdaName.put(mapList.get(i).getNameBackstage(),mapList.get(i));
                                }
                            }
                        }


                        if (entity.getDicText() == null){
                            isNeedWaring = true;
                            desString = "采集数据不能为空！";
                        }else {
                            JSONObject saveJsonObject = JSONObject.parseObject(entity.getDicText());
                            if (saveJsonObject == null){
                                saveJsonObject = new JSONObject();
                            }

                            JSONObject processJsonObject = JSONObject.parseObject(proRouteProcess.getParamJson());
                            Set<String> processKeys = processJsonObject.keySet();


                            for (String key: processKeys) {
                                String value = processJsonObject.getString(key);
                                if (value != null){
                                    int a = value.indexOf("(");
                                    if (a >= 0){
                                        value = value.substring(0,a);
                                    }
                                }

                                RecProcessesExt item = mapPdaName.get(key);
                                if (item == null){
                                    continue;
                                }
                                String padName = item.getNamePda();

                                if (StringUtils.isEmpty(padName)){
                                    isNeedWaring = true;
                                    desString = desString +"【"+key+"】没有配置采集参数的字段名称！";
                                }else {
                                    String saveValue = saveJsonObject.getString(padName);
                                    if (saveValue != null){
                                        int b = saveValue.indexOf("(");
                                        if (b >= 0) {
                                            saveValue = saveValue.substring(0, b);
                                        }
                                    }

                                    if (value.startsWith("≤")){
                                        //判断小于等于
                                        if (!StringUtils.isEmpty(saveValue)){
                                            if (Double.valueOf(saveValue.toString()) > Double.valueOf(value.replace("≤",""))){
                                                isNeedWaring = true;
                                                desString = desString +"【"+padName+"】是"+value+",但此记录是："+saveValue+"。";
                                            }
                                        }
                                    }else if (value.startsWith("≥")){
                                        //判断大于等于
                                        if (!StringUtils.isEmpty(saveValue)){
                                            if (Double.valueOf(saveValue.toString()) < Double.valueOf(value.replace("≥", ""))) {
                                                isNeedWaring = true;
                                                desString = desString +"【" + padName + "】是" + value + ",但此记录是：" + saveValue+"。";
                                            }
                                        }
                                    }else if(value.equals("Y")){
                                        //判断字段必须
                                        if (StringUtils.isEmpty(saveValue) || saveValue.equals("0") || saveValue.equals("否")){
                                            isNeedWaring = true;
                                            if (!StringUtils.isEmpty(saveValue)){
                                                desString = desString +"【"+padName+"】是必须的,但此记录是:"+saveValue+"。";
                                            }

                                        }
                                    }else if(value.contains("-")){
                                        String[] list1 = value.split("-");

                                        double max = Double.valueOf(list1[1]).doubleValue();
                                        double min = Double.valueOf(list1[0]).doubleValue();
                                        if (saveValue != null){
                                            double tsValue = Double.valueOf(saveValue).doubleValue();
                                            if (tsValue > max || tsValue < min){
                                                isNeedWaring = true;
                                                desString = desString +"【"+padName+"】是在"+min+"-"+max+"之间,但此记录是:"+saveValue+"。";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (isNeedWaring){
                        proWaring.setDes(desString);
                        insert(proWaring);
                    }
                }catch (Exception e){
                    log.error("数据采集警报",e);
                    String des = e.getLocalizedMessage();
                    proWaring.setDes(des);
                    insert(proWaring);
                }
            }
        }).start();
    }


}
